package com.alkaid.reflectionlearn;

import com.alkaid.annotation.WakeUp;
import com.alkaid.entity.Impl.PersonImpl;
import com.alkaid.proxy.TimingProxy;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.lang.reflect.Field;

@SpringBootApplication
public class ReflectionLearnApplication {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException {
//        SpringApplication.run(ReflectionLearnApplication.class, args);

        // 获取 class 对象
        Class<?> clazz = PersonImpl.class;
        System.out.println(clazz);

        clazz = Class.forName("com.alkaid.entity.Impl.PersonImpl");
        System.out.println(clazz);

        PersonImpl person = new PersonImpl();
        clazz = person.getClass();
        System.out.println(clazz);

        if (PersonImpl.class == Class.forName("com.alkaid.entity.Impl.PersonImpl")
                && PersonImpl.class == person.getClass()) {
            System.out.println("三者返回值相同");
        }

//        showObject(new PersonImpl("bob", 20, "boy"));
//        showObject(new PersonImpl("alice", 21, "girl"));
//        showObject(new PersonImpl("henry", 25, "man"));

        // 注解处理
        WakeUp wakeUp = clazz.getMethod("speak", String.class).getAnnotation(WakeUp.class);
        System.out.println(wakeUp.value());
        wakeUp = clazz.getMethod("eat", String.class).getAnnotation(WakeUp.class);
        System.out.println(wakeUp.value());
        wakeUp = clazz.getMethod("run", Integer.class).getAnnotation(WakeUp.class);
        System.out.println(wakeUp.value());

        // 动态代理
        TimingProxy.createProxy(new PersonImpl("bob", 20, "boy")).speak("happy new year");
        TimingProxy.createProxy(new PersonImpl("alice", 21, "girl")).eat("roast potato and beef");
        TimingProxy.createProxy(new PersonImpl("henry", 25, "man")).run(500);


    }

    public static void showObject(Object object) throws IllegalAccessException {
        // 获取字节码文件对象
        Class clazz = object.getClass();

        // 获取全部成员变量
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);

            String name = field.getName();
            Object value = field.get(object);

            System.out.println(name + " " + value);
        }
    }

}
